#include <my_header.h>

int main(){

    char *ip = "192.168.40.128";
    char *port = "8080";

    int socketFD = socket(AF_INET, SOCK_STREAM, 0);
    ERROR_CHECK(socketFD, -1, "socket");

    int rest;
    int ret = setsockopt(socketFD, SOL_SOCKET, SO_REUSEADDR, &rest, sizeof(rest));
    ERROR_CHECK(ret, -1, "setsockopt");

    struct sockaddr_in Addr;
    Addr.sin_family = AF_INET;
    Addr.sin_port = htons(atoi(port));
    Addr.sin_addr.s_addr = inet_addr(ip);

    ret = connect(socketFD, (struct sockaddr *)&Addr, sizeof(Addr));
    ERROR_CHECK(ret, -1, "connect");

    int epollFD = epoll_create(1);
    ERROR_CHECK(epollFD, -1, "epollFD");

    struct epoll_event event;
    event.events = EPOLLIN;
    event.data.fd = socketFD;
    ret = epoll_ctl(epollFD, EPOLL_CTL_ADD, socketFD, &event);
    ERROR_CHECK(ret, -1, "epoll_ctl_netfd");

    event.data.fd = STDIN_FILENO;
    ret = epoll_ctl(epollFD, EPOLL_CTL_ADD, STDIN_FILENO, &event);
    ERROR_CHECK(ret, -1, "epoll_ctl_STDIN");
    while(1){
        struct epoll_event ev[2];

        int ready_num = epoll_wait(epollFD, ev, 2, -1);
        ERROR_CHECK(ready_num, -1, "epoll_wait");

        for(int i = 0; i < ready_num; i++){
            if(ev[i].data.fd == socketFD){
                char buf[1024] = { 0 };
                ret = recv(socketFD, buf, sizeof(buf), 0);
                ERROR_CHECK(ret, -1, "recv");
                if(ret == 0){
                    exit(0);
                }

                ret = write(STDOUT_FILENO, "A:", strlen("A:"));
                ERROR_CHECK(ret, -1, "write");
                ret = write(STDOUT_FILENO, buf, strlen(buf));
                ERROR_CHECK(ret, -1, "write");
            }else{
                char buf[1024] = { 0 };
                ret = read(STDIN_FILENO, buf, sizeof(buf));
                ERROR_CHECK(ret, -1, "read");

                ret = send(socketFD, buf, strlen(buf), 0);
                ERROR_CHECK(ret, -1, "write");
            }
        }

    }

    close(socketFD);

    return 0;
}

